package com.totoro.web;
/**
 *by wangyeqing
 * 评阅论文
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.totoro.domain.MySysRemarkTemplate;
import com.totoro.domain.Project;
import com.totoro.domain.ReviewProject;
import com.totoro.domain.Tutor;
import com.totoro.service.MySysRemarkTemplateService;
import com.totoro.service.ProjectService;
import com.totoro.service.ReviewProjectService;
import com.totoro.service.StaffService;

@Controller
@RequestMapping("/review")
public class ReviewProjectController {
	@Autowired
	private ReviewProjectService reviewProjectService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private MySysRemarkTemplateService mySysRemarkTemplateService;
	
	@RequestMapping("/review.html")
	public String  list(Authentication authentication,Model model){
		Collection<ReviewProject> reviewProjects = this.findTutorByAuthentication(authentication).getReviewProject();
		model.addAttribute("reviewProjects", reviewProjects);
		return "/review/list";
	}
	@RequestMapping("/update/{id}.html")
	public String update(@PathVariable("id") String id,Model model,Authentication authentication) {
		
		ReviewProject reviewProject =  this.findReviewProjectByProjectId(id);
		if(reviewProject!=null){
			model.addAttribute("projectId", id);
			model.addAttribute("reviewProject", reviewProject);
			model.addAttribute("remarkTemplate", this.filterRemarkTemplate("评阅",this.findTutorByAuthentication(authentication).getMySysRemarkTemplate()));
		}
		
		return "/review/update";
		
	}
	
	private List<MySysRemarkTemplate> filterRemarkTemplate(String key,
			Collection<MySysRemarkTemplate> mySysRemarkTemplates) {
		List<MySysRemarkTemplate> list = new ArrayList<MySysRemarkTemplate>();
		Iterator<MySysRemarkTemplate> it = mySysRemarkTemplates.iterator();
		while (it.hasNext()) {
			MySysRemarkTemplate t = it.next();
			if(t.getKeyword().contains(key)){
				list.add(t);
			}
		}
		return list;
	}
	//保存
	@RequestMapping("/save.html")
	public String  save(@RequestParam("projectId") String projectId,ReviewProject reviewProject,Authentication authentication){
		ReviewProject old =  this.updateOldReivewProject(reviewProject,projectId);
		old.setState(true);
		reviewProjectService.update(old);
		return "redirect:/review/review.html";
	}
	
	//暂存
	@RequestMapping("/temporary.html")
	public String  temporary(@RequestParam("projectId") String projectId,ReviewProject reviewProject,Authentication authentication){
		ReviewProject old =  this.updateOldReivewProject(reviewProject,projectId);
		old.setState(false);
		reviewProjectService.update(old);
		return "redirect:/review/review.html";
	}
	
	@RequestMapping("/excel/{projectId}.html")
	public String excel(@PathVariable("projectId") String projectId,Model model,Authentication authentication){
		Project project = this.findProjectById(projectId);
		List<ReviewProject> list = (List<ReviewProject>) project.getReviewProject();
		if(list!=null && list.size()>0){
			model.addAttribute("reviewProject", list.get(0));
		}
		model.addAttribute("tutorName", this.findTutorByAuthentication(authentication).getName());
		model.addAttribute("project", project);
		return "reviewProjectExcel";
	}
	
	//增加评语时如果
	   @RequestMapping(value = "/getRemarkTemplateByKeyword.html", method = RequestMethod.POST)
	    public Object getRemarkTemplateKeywords(Authentication authentication, Model model, String keyword) {
	        Tutor tutor = staffService.uniqueResult("no", authentication.getName());
	        List<MySysRemarkTemplate> list = mySysRemarkTemplateService.list("actor", tutor);
	        
	        boolean isDuplicated = false;
	        
	        for (MySysRemarkTemplate template : list) {
	            if (template.getKeyword().equals(keyword)) {
	                isDuplicated = true;
	                break;
	            }
	        }
	        
	        model.addAttribute("isDuplicated", isDuplicated);
	        System.out.println("===================="+isDuplicated);
	        return "remarkTemplateKeywordsJson";
	    }	
	
	//增加评语模板json视图
    @RequestMapping(value="/saveToTemplate.html",method=RequestMethod.POST)
    public Object toTemplate(@ModelAttribute("mySysRemarkTemplate") MySysRemarkTemplate mySysRemarkTemplate,Authentication authentication,Model model){
    	Collection<MySysRemarkTemplate> collection = this.findTutorByAuthentication(authentication).getMySysRemarkTemplate();
    	
    	
    	Iterator<MySysRemarkTemplate> it = collection.iterator();
    	int flag = 0;
    	while (it.hasNext()) {
			MySysRemarkTemplate rt = (MySysRemarkTemplate) it
					.next();
			if(rt.getKeyword().equals(mySysRemarkTemplate.getKeyword())){
				Integer id = mySysRemarkTemplateService.list("keyword", mySysRemarkTemplate.getKeyword()).get(0).getId();
				mySysRemarkTemplate.setId(id);
				flag = -1;
			}
		}
    	if(flag>=0){
    		mySysRemarkTemplate.setActor(this.findTutorByAuthentication(authentication));
    		mySysRemarkTemplateService.save(mySysRemarkTemplate);
    		flag = 1;
    	}else {
    		mySysRemarkTemplate.setActor(this.findTutorByAuthentication(authentication));
    		mySysRemarkTemplateService.merge(mySysRemarkTemplate);
    		
		}
    	model.addAttribute("code", flag);
        return "remarkTemplateKeywordsJson";
    }
	private ReviewProject updateOldReivewProject(ReviewProject reviewProject,String projectId) {
		this.checkScore(reviewProject);
		ReviewProject old = this.findReviewProjectByProjectId(projectId);
		old.setDocQualityScore(reviewProject.getDocQualityScore());
		old.setAchievementLevel(reviewProject.getAchievementLevel());
		old.setRemark(reviewProject.getRemark());
		return old;
	}
	private void checkScore(ReviewProject reviewProject) {
		if(reviewProject.getAchievementLevel()==null||reviewProject.getAchievementLevel()<0){
			reviewProject.setAchievementLevel(0);
		}
		if(reviewProject.getDocQualityScore()==null || reviewProject.getDocQualityScore()<0){
			reviewProject.setDocQualityScore(0);
		}
		
	}
	private ReviewProject findReviewProjectByProjectId(String id) {
		Project project = projectService.get(new Integer(id));
		List<ReviewProject> list = (List<ReviewProject>) project.getReviewProject();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}
	private Project findProjectById(String id) {
		Project project = projectService.get(new Integer(id));
		return project;
	}
	
	private Tutor findTutorByAuthentication(Authentication authentication){
		
		Tutor tutor = staffService.uniqueResult("no", authentication.getName()); 
		if(tutor!=null){
			return tutor;
		}
		return null;
	}
	
}
